import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Spin } from 'antd';
import EditPage from '@/components/EditPage';
import DetailPage from '@/components/DetailPage';
import FileReader from '@/components/FileReader';
import PartsOfferInfo from './PartsOfferInfo';
import { formItemFragement } from '@/utils/common';
import { allDictList } from '@/utils/constans';
import { renderTableAdSelect, allDispatchType } from './utils';

@connect(({ partsOffer, component, loading }) => ({
  partsOfferDetail: partsOffer.partsOfferDetail,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.detail],
}))
export default class PartsOfferDetail extends Component {
  state = {
    detailId: '',
  };

  componentDidMount() {
    const { id } = this.props;
    this.handleStateChange([{ detailId: id }]);
    this.selectPartsOfferDetail(id);
  }

  componentWillReceiveProps(nextProps) {
    const { id } = nextProps;
    if (this.props.id !== id) {
      this.handleStateChange([{ detailId: id }]);
      this.selectPartsOfferDetail(id);
    }
  }

  selectPartsOfferDetail = id => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.detail,
      payload: { id },
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  render() {
    const { loading, partsOfferDetail } = this.props;
    const { detailId } = this.state;
    const detail = partsOfferDetail[detailId];
    const { offerNo, mdsCompanyId, offerDate, effeTimeBegin, effeTimeEnd, fileList } = detail || {};
    const editPageParams = {
      panelTitle: ['基础信息', '明细'],
    };
    const formItem = [
      [
        <DetailPage label="单号" value={offerNo} />,
        <DetailPage
          label="供应商名称"
          value={renderTableAdSelect({
            props: this.props,
            value: mdsCompanyId,
            key: allDictList.partsSupplier,
          })}
        />,
      ],
      [
        <DetailPage label="报价日期" value={offerDate} />,
        <DetailPage
          label="有效期"
          value={effeTimeBegin ? `${effeTimeBegin}~${effeTimeEnd}` : ''}
        />,
      ],
      [
        <DetailPage
          label="附件"
          value={
            <FileReader
              value={fileList}
              showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
              showUpload={false}
              urlType="tms"
            />
          }
        />,
      ],
    ];
    return (
      <EditPage {...editPageParams}>
        <Spin spinning={loading}>{formItemFragement(formItem)}</Spin>
        <Fragment>
          <PartsOfferInfo id={detailId} />
        </Fragment>
      </EditPage>
    );
  }
}
